"""
KML Thememap builder
python themebuilder.py -d files/samplefiles/bigtest.csv -o me.kmz -p files/kmlsource/theworld.kml
by emeijdam@gmail.com"""

import xml.dom.minidom
import zipfile
import os
import sys
from optparse import OptionParser

from math import *


#History
#    2009-4-1   release 0.00000001

__author__  =  'emeijdam'
__version__ =  '0.0.1'
version = __version__

datafile = ''
polygonkml = ''
outfilekmz = ''
logofile = 'files/images/phaena.png'
legendfile = 'files/images/legend.png'
smallegend = 'files/images/smalllegend.png'
#colorMax = 'ff0000'
colorMax = '000000'
colorMin = 'ffffff'
opacity = 'ff'
minH = float(10000.0)
maxH = float(40000.0)


###
#
# Convert (x,y,z) on unit sphere
# back to (long, lat)
#
# p is vector of three elements
# 
def toEarth(p):
    if (p[0] == 0.0):
        longitude = pi / 2.0
    else:
        longitude = atan(p[1]/p[0])
    colatitude = acos(p[2]);
    latitude = (pi / 2.0 - colatitude)

    # select correct branch of arctan
    if p[0] < 0.0:
        if p[1] <= 0.0:
            longitude = -(pi - longitude)
        else:
            longitude = pi + longitude

    DEG = 180.0 / pi
    return [longitude * DEG, latitude * DEG]


#
# convert long, lat IN RADIANS to (x,y,z)
# 
def toCart(longitude, latitude):
    theta = longitude
    # spherical coordinate use "co-latitude", not "lattitude"
    # lattiude = [-90, 90] with 0 at equator
    # co-latitude = [0, 180] with 0 at north pole
    phi = pi / 2.0 - latitude
    return [ cos(theta) * sin(phi), sin(theta) * sin(phi), cos(phi)]

# spoints -- get raw list of points in long,lat format
#
# meters: radius of polygon
# n: number of sides
# offset: rotate polygon by number of degrees
#
# Returns a list of points comprising the object
#
def spoints(long, lat, meters, n, offset=0):
    # constant to convert to radians
    RAD = pi / 180.0;
    # Mean Radius of Earth, meters
    MR = 6378.1 * 1000.0;
    offsetRadians = offset * RAD
    # compute longitude degrees (in radians) at given latitude
    r = (meters / (MR * cos(lat * RAD)))

    vec = toCart(long * RAD, lat * RAD)
    pt = toCart(long * RAD + r, lat * RAD)
    pts = [ ]

    for i in range(0,n):
        pts.append(toEarth(rotPoint(vec, pt, offsetRadians + (2.0 * pi/n)*i)))

    # connect to starting point exactly
    # not sure if required, but seems to help when
    # the polygon is not filled
    pts.append(pts[0])
    return pts

#
# rotate point pt, around unit vector vec by phi radians
# http://blog.modp.com/2007/09/rotating-point-around-vector.html
# 
def rotPoint(vec, pt,  phi):
    # remap vector for sanity
    (u,v,w,x,y,z) = (vec[0],vec[1],vec[2], pt[0],pt[1],pt[2])

    a = u*x + v*y + w*z;
    d = cos(phi);
    e = sin(phi);

    return [ (a*u + (x - a*u)*d + (v*z - w*y) * e),
             (a*v + (y - a*v)*d + (w*x - u*z) * e),
             (a*w + (z - a*w)*d + (u*y - v*x) * e) ]

#
# Regular polygon
# (longitude, latitude) in decimal degrees
# meters is radius in meters
# segments is number of sides, > 20 looks like a circle
# offset, rotate polygon by a number of degrees
#
# returns a string suitable for adding to a KML file.
#
# You may want to
#  edit this function to change "extrude" and other XML nodes.
#

###


def getText(nodelist):
    rc = ""
    for node in nodelist:
		if node.nodeType == node.TEXT_NODE:
			rc = node.data.strip()
    return rc

def retrievePlacemarksInKML(nodelist):
	placemarklist = []
	for place in nodelist:
		placename = place.getElementsByTagName("name")[0]
		placemarklist.append(getText(placename.childNodes))
	return placemarklist
	
def retrieveColorDict(nodelist):
	placemarkColorDict = {}
	for place in nodelist:
		placename = place.getElementsByTagName("name")[0]
		color = place.getElementsByTagName("color")[0]
		#print getText(placename.childNodes)
		#print getText(color.childNodes)
		placemarkColorDict[getText(placename.childNodes)] = getText(color.childNodes)
	return placemarkColorDict

		
		
def handleCoordinates(nodelist, placenameText):
	newlist = []
	placemarklist = []
	for place in nodelist:
		placename = place.getElementsByTagName("name")[0]
		if (placenameText.lower() == getText(placename.childNodes).lower()):
			coords = place.getElementsByTagName("coordinates")
			#print "coord found:", len(coords)
			for coord in coords:
				coord2 = getText(coord.childNodes)
				
				alist = []
				for line in coord2.splitlines():
					points = line.split(' ')
					for point in points:
						#print 'point', point
						#print len(points)
						if(len(points) > 3):
							split = point.split(' ')
							line2 = split[0]
							#print 'line', line
							split = line2.split(',')
							if(len(split) == 3):
								#print 'line', line2
								#print 'split', split
								x,y,z = split
								alist.append([float(x),float(y),float(z)])
								#print 'alist: ', x , y, z
							elif (len(split) == 2):
								split.append(str(0))
								x,y,z = split
								alist.append([float(x),float(y),float(z)])
							else:
								split = line.split(',')
								if(len(split) == 3):
									#print 'line', line
									#print 'split', split
									x,y,z = split
									alist.append([float(x),float(y),float(z)])
									#print 'alist: ', x , y, z
								elif (len(split) == 2):
									split.append(str(0))
									x,y,z = split
									alist.append([float(x),float(y),float(z)])
						elif (len(points) == 1):
							#print point
							split = point.split(',')
							x,y,z = split
							alist.append([float(x),float(y),float(z)])
							
				newlist.append(alist)
				#print 'new', newlist		
	return newlist

def get_a_document(name="testme3.kml"):
    return xml.dom.minidom.parse(name)

def compareDictToPlacemarkList(sourcelist, kmlsource):
	sourcelist = map(lowerme,sourcelist)
	kmlsource = map(lowerme,kmlsource)
	notfound = [val for val in sourcelist if val not in kmlsource]

	found = [val for val in kmlsource if val in sourcelist]
	if (len(notfound) > 0):
		print "The coordinates of this placemark could not be found:"
		print notfound
	return found

def lowerme(text): return text.lower()

def lookupDictionaryKeysInPlacemarks(lookupDict, sourceKml):
	sourcelist = []
	for k, v in lookupDict.iteritems():
		sourcelist.append(k)
		
	nodelist = sourceKml.getElementsByTagName('Placemark')
	retrievePlacemarks =  retrievePlacemarksInKML(nodelist)
	placesfound = compareDictToPlacemarkList(sourcelist, retrievePlacemarks )
	coordDict = {}
	if (len(placesfound) != 0):
		for place in placesfound:
			coordDict[place] = handleCoordinates(nodelist, place)
	return coordDict
	

def lookupPlaceinPlacemarks(place, sourceKml):
	#aanpassen
	nodelist = sourceKml.getElementsByTagName('Placemark')
	retrievePlacemarks =  retrievePlacemarksInKML(nodelist)
	#print 'retr', retrievePlacemarks
	placesfound = compareDictToPlacemarkList([place], retrievePlacemarks )
	#print 'places', placesfound
	if (len(placesfound) != 0):
		polygoncoordinatesList = handleCoordinates(nodelist, place)
		#print 'hallo', polygoncoordinatesList
	else:
		polygoncoordinatesList = []
	return polygoncoordinatesList

def RGBToHTMLColor(rgb_tuple):
    """ convert an (R, G, B) tuple to #RRGGBB """
    hexcolor = '%02x%02x%02x' % rgb_tuple
    # that's it! '%02x' means zero-padded, 2-digit hex values
    return hexcolor

def HTMLColorToRGB(colorstring):
    """ convert #RRGGBB to an (R, G, B) tuple """
    colorstring = colorstring.strip()
    if colorstring[0] == '#': colorstring = colorstring[1:]
    if len(colorstring) != 6:
        raise ValueError, "input #%s is not in #RRGGBB format" % colorstring
    r, g, b = colorstring[:2], colorstring[2:4], colorstring[4:]
    r, g, b = [int(n, 16) for n in (r, g, b)]
    return (r, g, b)

def test(tupFirst, tupLast, p):
	#print tupFirst[0], tupLast[0]
	#print tupFirst[1], tupLast[1]
	#print tupFirst[2], tupLast[2]
	r = tupFirst[0] * p + tupLast[0] * (1 - p)
	g = tupFirst[1] * p + tupLast[1] * (1 - p)
	b = tupFirst[2] * p + tupLast[2] * (1 - p)
	#print r, g, b
	rgb = (r, g, b)
	return RGBToHTMLColor(rgb)

def vdict2pdict(value_dict):
	mymax = max(value_dict, key = lambda x: value_dict.get(x) )
	mymin = min(value_dict, key = lambda x: value_dict.get(x) )
	pdict = value_dict.copy()
	for k, v in pdict.iteritems():
		pdict[k] =  (float(float(value_dict[k]) - float(value_dict[mymin])) / float(value_dict[mymax] - float(value_dict[mymin])))
	return pdict

def vdict2Hdict(value_dict):
	mymax = max(value_dict, key = lambda x: value_dict.get(x) )
	mymin = min(value_dict, key = lambda x: value_dict.get(x) )
	global minH # = float(10000.0)
	global maxH #= float(400000.0) 
	
	Hdict = value_dict.copy()
	for k, v in Hdict.iteritems():
		Hdict[k] =  (float(float(value_dict[k]) - float(value_dict[mymin])) * (maxH - minH) / float(value_dict[mymax] - float(value_dict[mymin]))) + minH
	return Hdict

def dictToColor(dict):
	global colorMax
	global colorMin
	tupRed = HTMLColorToRGB(colorMin)
	tupBlue = HTMLColorToRGB(colorMax)
	dictColor = vdict2pdict(dict)
	for k, v in dictColor.iteritems():
		dictColor[k] =  test(tupBlue, tupRed, v)
	return dictColor
	
def create_style(kmlDoc, id=''):
	#Style
	styleElement = kmlDoc.createElement('Style')
	if (id!=''):
		styleElement.setAttribute( "id", id )
	
	iconElement = kmlDoc.createElement('Icon')

	hrefElement = kmlDoc.createElement('href')
	hrefText = kmlDoc.createTextNode('phaena_logo_200_30.png')
	hrefElement.appendChild(hrefText)

	iconElement.appendChild(hrefElement)
	styleElement.appendChild(iconElement)
	
	#Style:Polystyle
	polystyleElement = kmlDoc.createElement('PolyStyle')
	
	#Style:Polystyle:Color
	colorElement = kmlDoc.createElement('color')
	colorText = kmlDoc.createTextNode('ff000000')
	colorElement.appendChild(colorText)
	
	#Style:Polystyle:outline
	outlineElement = kmlDoc.createElement('outline')
	outlineText = kmlDoc.createTextNode('1')
	outlineElement.appendChild(outlineText)
	
	polystyleElement.appendChild(colorElement)
	polystyleElement.appendChild(outlineElement)
	
	styleElement.appendChild(polystyleElement)
	
	#Style:LineStyle
	linestyleElement = kmlDoc.createElement('LineStyle')
	
	#Style:LineStyle:Color
	colorElement = kmlDoc.createElement('color')
	colorText = kmlDoc.createTextNode('ff000000')
	linestyleElement.appendChild(colorText)
	
	styleElement.appendChild(linestyleElement)
	
	#Style:BalloonStyle
	balloonstyleElement = kmlDoc.createElement('BalloonStyle')
	
	#Style:BalloonStyle:text
	textElement = kmlDoc.createElement('text')
	textText = kmlDoc.createTextNode('bla bla')
	textElement.appendChild(textText)
	
	balloonstyleElement.appendChild(textElement)
	
	styleElement.appendChild(balloonstyleElement)
	
	return styleElement

def create_ScreenOverlay(kmlDoc, imagefile, pos):
	screenoverlayElement = kmlDoc.createElement('ScreenOverlay')
	
	screenoverlayElement.appendChild(createNameElement(kmlDoc,'Title'))
	
	iconElement = kmlDoc.createElement('Icon')
	
	hrefElement = kmlDoc.createElement('href')
	hrefText = kmlDoc.createTextNode(imagefile)
	hrefElement.appendChild(hrefText)
	
	iconElement.appendChild(hrefElement)
	screenoverlayElement.appendChild(iconElement)
	if pos == 'logo':
	    overlayxyElement = kmlDoc.createElement('overlayXY')
	    overlayxyElement.setAttribute('x', '0.01')
	    overlayxyElement.setAttribute('y', '0.99')
	    overlayxyElement.setAttribute('xunits', 'fraction')
	    overlayxyElement.setAttribute('yunits', 'fraction')

	    screenxyElement = kmlDoc.createElement('screenXY')
	    screenxyElement.setAttribute('x', '0.01')
	    screenxyElement.setAttribute('y', '0.99')
	    screenxyElement.setAttribute('xunits', 'fraction')
	    screenxyElement.setAttribute('yunits', 'fraction')

	    sizeElement = kmlDoc.createElement('size')
	    sizeElement.setAttribute('x', '-1')
	    sizeElement.setAttribute('y', '-1')
	    sizeElement.setAttribute('xunits', 'pixels')
	    sizeElement.setAttribute('yunits', 'pixels')
	elif pos == 'legend':
	    overlayxyElement = kmlDoc.createElement('overlayXY')
	    overlayxyElement.setAttribute('x', '0')
	    overlayxyElement.setAttribute('y', '0')
	    overlayxyElement.setAttribute('xunits', 'fraction')
	    overlayxyElement.setAttribute('yunits', 'fraction')

	    screenxyElement = kmlDoc.createElement('screenXY')
	    screenxyElement.setAttribute('x', '5')
	    screenxyElement.setAttribute('y', '15')
	    screenxyElement.setAttribute('xunits', 'pixels')
	    screenxyElement.setAttribute('yunits', 'pixels')

	    sizeElement = kmlDoc.createElement('size')
	    sizeElement.setAttribute('x', '100')
	    sizeElement.setAttribute('y', '200')
	    sizeElement.setAttribute('xunits', 'pixel')
	    sizeElement.setAttribute('yunits', 'pixel')

	
	screenoverlayElement.appendChild(overlayxyElement)
	screenoverlayElement.appendChild(screenxyElement)
	screenoverlayElement.appendChild(sizeElement)
	
	return screenoverlayElement

def create_PolyStyle(kmlDoc, color, outline = '1'):
	#Style:Polystyle
	polystyleElement = kmlDoc.createElement('PolyStyle')
	
	#Style:Polystyle:Color
	colorElement = kmlDoc.createElement('color')
	colorText = kmlDoc.createTextNode(color)
	colorElement.appendChild(colorText)
	
	#Style:Polystyle:outline
	outlineElement = kmlDoc.createElement('outline')
	outlineText = kmlDoc.createTextNode(outline)
	outlineElement.appendChild(outlineText)
	
	polystyleElement.appendChild(colorElement)
	polystyleElement.appendChild(outlineElement)
	
	return polystyleElement
	
def create_stylemap(kmlDoc):
	#Stylemap
	stylemapElement = kmlDoc.createElement('StyleMap')
	stylemapElement.setAttribute( "id", "stylemapname" )
	
	#PairNormal
	pairnormalElement = kmlDoc.createElement('Pair')
	
	keyElement = kmlDoc.createElement('key')
	keyText = kmlDoc.createTextNode('normal')
	keyElement.appendChild(keyText)
	
	styleUrlElement = kmlDoc.createElement('styleUrl')
	styleUrlText = kmlDoc.createTextNode('#stylename')
	styleUrlElement.appendChild(styleUrlText)
	
	pairnormalElement.appendChild(keyElement)
	pairnormalElement.appendChild(styleUrlElement)
	
	#PairHighLight
	pairhighlightElement = kmlDoc.createElement('Pair')
	
	keyElement = kmlDoc.createElement('key')
	keyText = kmlDoc.createTextNode('highlight')
	keyElement.appendChild(keyText)
	
	styleUrlElement = kmlDoc.createElement('styleUrl')
	styleUrlText = kmlDoc.createTextNode('#stylename')
	styleUrlElement.appendChild(styleUrlText)
	
	pairhighlightElement.appendChild(keyElement)
	pairhighlightElement.appendChild(styleUrlElement)
	
	stylemapElement.appendChild(pairnormalElement)
	stylemapElement.appendChild(pairhighlightElement)
	return stylemapElement

def createNameElement(kmlDoc, name):
	nameElement = kmlDoc.createElement('name')
	nameText = kmlDoc.createTextNode(name)
	nameElement.appendChild(nameText)
	return nameElement
	
def create_place_mark(kmlDoc, name, pointCoordinates = [], polygonCoordinates = [], color='',height=0):
	placemarkElement = kmlDoc.createElement('Placemark')
	#print name
	placemarkElement.appendChild(createNameElement(kmlDoc, name))
	
	descriptionElement = kmlDoc.createElement('description')
	descriptionText = kmlDoc.createTextNode('address')
	descriptionElement.appendChild(descriptionText)
	
	placemarkElement.appendChild(descriptionElement)
	
	styleUrlElement = kmlDoc.createElement('styleUrl')
	styleUrlText = kmlDoc.createTextNode('#stylename')
	styleUrlElement.appendChild(styleUrlText)
	placemarkElement.appendChild(styleUrlElement)

	if (color!=''):
		styleElement = kmlDoc.createElement('Style')
		styleElement.appendChild(create_PolyStyle(kmlDoc, color))
		placemarkElement.appendChild(styleElement)
	
	placemarkElement.appendChild(create_MultiGeometry(kmlDoc, pointCoordinates, polygonCoordinates, height))
	
	return placemarkElement
	
def create_MultiGeometry(kmlDoc, pointCoordinates = [], polygonCoordinates=[], height=0):
	multigeometryElement = kmlDoc.createElement('MultiGeometry')
	extrudeElement = kmlDoc.createElement('extrude')
	extrudeText = kmlDoc.createTextNode('1')
	extrudeElement.appendChild(extrudeText)
	multigeometryElement.appendChild(extrudeElement)
	#multigeometryElement.appendChild(create_Point(kmlDoc,pointCoordinates))
	for polygonCoordinate in polygonCoordinates:
		#print "number:", len(polygonCoordinates)

		multigeometryElement.appendChild(create_Polygon(kmlDoc,polygonCoordinate, height))
	return multigeometryElement

def create_Point(kmlDoc,coordinateList = []):
	pointElement = kmlDoc.createElement('Point')
	#extrudeElement = kmlDoc.createElement('extrude')
	#extrudeText = kmlDoc.createTextNode('1')
	#extrudeElement.appendChild(extrudeText)
	#pointElement.appendChild(extrudeElement)
	
	coordinatesElement = kmlDoc.createElement('coordinates')
	if (coordinateList == []):
		coordinatesText =  kmlDoc.createTextNode('3,4')
	else:
		x, y = coordinateList
		coordinatesText = kmlDoc.createTextNode(str(x) + ',' + str(y))
	coordinatesElement.appendChild(coordinatesText)
	pointElement.appendChild(coordinatesElement)
	
	#altitudemodeElement = kmlDoc.createElement('altitudeMode')
	#altitudemodeText = kmlDoc.createTextNode('absolute')
	#altitudemodeElement.appendChild(altitudemodeText)
	#pointElement.appendChild(altitudemodeElement)
	
	return pointElement

def create_Polygon(kmlDoc, coordinatesList=[], height=0):
	polygonElement = kmlDoc.createElement('Polygon')
	
	extrudeElement = kmlDoc.createElement('extrude')
	extrudeText = kmlDoc.createTextNode('1')
	extrudeElement.appendChild(extrudeText)
	polygonElement.appendChild(extrudeElement)
	
	altitudemodeElement = kmlDoc.createElement('altitudeMode')
	if (height != 0): 
		altitudemodeText = kmlDoc.createTextNode('relativeToGround')
	else:
		altitudemodeText = kmlDoc.createTextNode('clampToGround')
	altitudemodeElement.appendChild(altitudemodeText)
	polygonElement.appendChild(altitudemodeElement)
	
	outerBoundaryIsElement = kmlDoc.createElement('outerBoundaryIs')
	linearringElement = kmlDoc.createElement('LinearRing')
	#print 'polyheight', height
	
	coordinatesElement = kmlDoc.createElement('coordinates')
	if(coordinatesList == []):
		coordinatesText =  kmlDoc.createTextNode('3,7')
	else:
		coordinatesText =  kmlDoc.createTextNode(polygonList2elementText(coordinatesList, height))
		
	coordinatesElement.appendChild(coordinatesText)
	linearringElement.appendChild(coordinatesElement)
		
	outerBoundaryIsElement.appendChild(linearringElement)
	polygonElement.appendChild(outerBoundaryIsElement)
	return polygonElement

def createKML(datadict, polygonkml, timedict= {}):
	# KML
	kmlDoc = xml.dom.minidom.Document()
	kmlElement = kmlDoc.createElementNS('http://earth.google.com/kml/2.2','kml')
	kmlElement = kmlDoc.appendChild(kmlElement)
	# Document
	documentElement = kmlDoc.createElement('Document')
	documentElement = kmlElement.appendChild(documentElement)
	
	#Open
	openElement = kmlDoc.createElement('open')
	openText = kmlDoc.createTextNode('1')
	openElement.appendChild(openText)
	
	documentElement.appendChild(openElement)
	
	documentElement.appendChild(create_ScreenOverlay(kmlDoc, logofile, pos='logo'))
	documentElement.appendChild(create_ScreenOverlay(kmlDoc, legendfile, pos='legend'))
	#Style
	styleElement = create_style(kmlDoc, 'stylename')
	documentElement.appendChild(styleElement)
	
	#Stylemap
	stylemapElement = create_stylemap(kmlDoc)
	documentElement.appendChild(stylemapElement)
	
	politie = datadict

	colorPol = dictToColor(politie);
	hoogte = vdict2Hdict(politie)
	
	polygonSourceKML = get_a_document(polygonkml)

	global opacity
	#Placemarks
	for k,v in sorted(politie.iteritems()):
	
		polygonList = lookupPlaceinPlacemarks(k, polygonSourceKML)
		for polygon in polygonList:
			if (polygonClockwise(polygon) == -1): polygon.reverse()
		
		if (len(polygonList) != 0):
			### DETERMINE LARGEST AREA
			centroidpoint = polygonCentroid(len(polygonList[0]), polygonList[0], polygonArea(polygonList[0]))

			placemarkElement = create_place_mark(kmlDoc, k, centroidpoint,polygonList, opacity + colorPol[k],hoogte[k])
			documentElement.appendChild(placemarkElement)
	return kmlDoc

def readshapefile(filename):
	f = open(filename,'r')
	z = 0
	polygonCoordinates = ''
	polygonList = []
	for line in f:
		x, y = line.split(",")
		x, y = float(x), float(y)
		polygonList.append([x, y, z])
	       # polygonCoordinates = polygonCoordinates + line.rstrip('\r\n') + ', ' + str(height) + ' '
	f.close()
	return polygonList

def polygonList2elementText(polygonList, height=0):
	coordinatesElementText = ''
	### CHECK CLOCKWISE
	#thislist = polygonList.reverse()
	#print 'polylist', polygonList
	#print '*' * 60
	#test = polygonList.reverse()
	#print 'polylist reverse', test
	#print '*' * 60
	#print 'polyheight', height
	for x, y, z in reversed(polygonList):
		if (height == 0):
			height = z
		coordinatesElementText = coordinatesElementText + str(x) + ',' + str(y) + ',' + str(int(round(height,0))) + '\n'
		#print coordinatesElementText
	return coordinatesElementText

def polygonArea(polygon):
	# number of points
	n = len(polygon)
	#print 'n: ', n
	#print polygon
	area = float(0.0)
	i = 0
	if(len(polygon[0]) == 2):
		for i, (h, v) in enumerate(polygon):
			j = (i + 1) % n
			nextX, nextY = polygon[(i + 1) % n]
			area += h * nextY - nextX * v
	else:
		#print 'else'
		for i, (h, v, z) in enumerate(polygon):
			j = (i + 1) % n
			nextX, nextY, z = polygon[(i + 1) % n]
			area += h * nextY - nextX * v
	area = area / 2
	return area
	
def polygonClockwise(polygon):
	CLOCKWISE = 1
	COUNTERCLOCKWISE = -1
	#print polygon
	mypoly = polygon[:]
	if (polygon[0] == polygon[len(polygon) - 1]):
		#print "removed last"
		
		mypoly.pop(len(polygon) - 1)
		#print polygon
		#print 'first', polygon[0]
		#print 'last', polygon[len(polygon) - 1]

	# number of points
	n = len(mypoly)
	#print 'n: ', n
	z = float(0.0)
	i = 0
	count = 0
	for i, (h, v, foo) in enumerate(mypoly):
		#j = (i + 1) % n
		#k = (i + 2) % n
		nexth, nextv, nextfoo = mypoly[(i + 1) % n] #j
		nextnexth, nextnextv, nextnextfoo = mypoly[(i + 2) % n] #k
		#print 'this', h, v
		#print "next", nexth, nexth
		z = (nexth - h) * (nextnextv - nextv)
	
		z -= (nextv - v) * (nextnexth - nexth)
		
		if (z < 0):
			#print 'z < ', z
			count -= 1
		elif (z > 0):
			#print 'z > ', z
			count += 1
	#print 'z = ', z		
	if (count > 0):
		return COUNTERCLOCKWISE
	else:
		return CLOCKWISE

def polygonCentroid(n, polygon, area):
	rX = 0
	rY = 0
	#print 'arie', area
	if(len(polygon[0]) == 2):
		for i, (h, v) in enumerate(polygon):
			j = (i + 1) % n
			nextX, nextY = polygon[(i + 1) % n]
			p = h * nextY - nextX * v
			rX = rX + (h + nextX) * p
			rY = rY + (v + nextY) * p
		rX = rX / (6 * area)
		rY = rY / (6 * area)
	else:
		for i, (h, v, z) in enumerate(polygon):
			j = (i + 1) % n
			nextX, nextY, x = polygon[(i + 1) % n]
			p = h * nextY - nextX * v
			rX = rX + (h + nextX) * p
			rY = rY + (v + nextY) * p
		rX = rX / (6 * area)
		rY = rY / (6 * area)	
	return [rX, rY]

def readCSVtoDicts(mfilename, placemarkVar, valueVar='', timeVar=''):
	import csv


	
	#print mfilename
	reader = csv.reader(open(mfilename))

	placemarkVar = placemarkVar.lower()
	#print 'place', placemarkVar
	valueVar = valueVar.lower()
	#print "val", valueVar
	timeVar = timeVar.lower()
    
	
	header = reader.next()
	# Header to lower
	for var in header:
		header[header.index(var)] = var.lower()

	valueDict = {}
	timeDict = {}
	
	indexDict = {}
	# temp removed timevar
	findinHeader = [placemarkVar, valueVar]
	#print header
	
	for var in findinHeader:
		if (var in header):
			indexDict[var] = header.index(var)
		else:
			print "var not found:", var
			return valueDict, timeDict
	
	for line in reader:
		#print line
		valueDict[line[indexDict[placemarkVar]]] = float(line[indexDict[valueVar]])
		#timeDict[line[indexDict[placemarkVar]]] = float(line[indexDict[timeVar]])
		
	#print "-" * 80
	#print "valueDict: ", valueDict
	##print "timeDict: ", timeDict
	if (timeDict == {}): return valueDict
	
	return valueDict, ['0']

def readCSVColumnNames(mfilename):
	import csv
	#print mfilename
	reader = csv.reader(open(mfilename))

	#placemarkVar = placemarkVar.lower()
	#valueVar = valueVar.lower()
	#timeVar = timeVar.lower()
    
	
	header = reader.next()
	# Header to lower
	for var in header:
		header[header.index(var)] = var.lower()

	
	return header

def save_kmzfile(kmzfilename,kmlfilename, kmlDoc):
	file = zipfile.ZipFile(kmzfilename, "w")
	info = zipfile.ZipInfo(kmlfilename)
	file.write(logofile,os.path.basename(logofile), zipfile.ZIP_DEFLATED, )
	file.write(legendfile,os.path.basename(legendfile), zipfile.ZIP_DEFLATED, )
	#Just add a folder to output
	info.compress_type = zipfile.ZIP_DEFLATED
	file.writestr(info, kmlDoc.toxml())
	file.close()
	
def run_earth(kmzfile):
	os.system("open -a 'Google Earth.app' " + kmzfile)

def save_kml(kmldoc, filename):
	f = open(filename,'w')
	f.write(kmldoc.toxml())
	f.close()

def tupColor(hexcolor):
	r = int(hexcolor[0:2],16)
	g = int(hexcolor[2:4],16)
	b = int(hexcolor[4:6],16)
	return r, g, b
	
def create_legend(title, labeltop='', labelmiddle='', labelbottom=''):
	from PIL import Image, ImageFont, ImageDraw, ImageOps
	
	global smalllegend
	global legendfile
	global colorMax
	global colorMin
	print tupColor(colorMax)
	
	edje = Image.new('RGB', (30, 200))
	imd = ImageDraw.Draw(edje)
	r1, g1, b1 = tupColor(colorMax)
	r2, g2, b2 = tupColor(colorMin)
	rV = abs(r1 - r2)
	gV = abs(g1 - g2)
	bV = abs(b1 - b2)
	Rstep = float(rV) / 200
	Gstep = float(gV) / 200
	Bstep = float(bV) / 200

	#print float(128 /200)
	xR= 0
	xG= 0
	xB= 0
	for l in xrange(200):
		#colour = (r1, g1, b1 * l / 100)
		xR += Rstep
		xG += Gstep
		xB += Bstep
		yR = int(xR)
		yG = int(xG)
		yB = int(xB)
		colour = (yR, yG, yB)
		imd.line((0, l, 30, l), fill=colour)
	
	edje.save(smallegend, 'PNG')


	words = [
	    ((50, 0), labeltop, "#ff0000", 30),
	    ((50, 95), labelmiddle, "#00ff00", 30),
	    ((50, 190), labelbottom, "#0000ff", 30),
	    ]

	# A fully transparent image to work on.
	im = Image.new("RGBA", (100, 300), (0,0,0,0))

	dr = ImageDraw.Draw(im)

	for pos, text, color, size in words:
	    font = ImageFont.load_default()
	    dr.text(pos, text, font=font, fill='White')


	#im.show()
	gradpy = edje #Image.open(smallegend)
	im.paste(gradpy,(12,0))

	dr.rectangle([12,0,40,200], outline='white')

	txt=Image.new('RGBA', (200,9), (0,0,0,0))
	d = ImageDraw.Draw(txt)
	d.text( (0, 0), title,  font=font, fill="White")

	w=txt.rotate(90,  expand=1)
	im.paste(w,(0,0))

	im.save(legendfile, "PNG")


def listprinter(alist, parts):
	s = ''
	partlist = []
	for index, item in enumerate(alist):
		partlist.append(str(index) + '=' + item)

	thestring = ''
	for index in range(parts):
		for item2 in partlist[index::parts]:
			thestring = thestring + ' ' + item2 + '\t'
		print thestring
		thestring = ''

def columnChooser(alist, question):
    print question
    listprinter(alist, 5)
    #print 'thelen',len(alist) - 1
    var = raw_input("Enter a column number: ")
    while not var.isdigit():
    	var = raw_input("Enter a column number: ")

    while not int(var) <= (len(alist) - 1):
        var = raw_input("Enter a column number: ")

    if alist[int(var)] in alist:
        print "you entered: ", var, "\t", alist[int(var)]
    return alist[int(var)]
    

def run():
    global datafile
    global outfile
    global polygonkml
    #datafile = options.datafile
    columnList = readCSVColumnNames(datafile)
    
    placevar = columnChooser(columnList, "Please choose the column containing the placemarks:")
    valuevar = columnChooser(columnList, "Please choose the column where you want to report over:")
    
    cvar = raw_input("continue: [Y/N]")
    if cvar == 'y':
    	
        data = readCSVtoDicts(datafile, placevar, valuevar)
	
        kmlDoc = createKML(data, polygonkml)
        create_legend('Color range', labeltop='Top', labelbottom='bottom')
        save_kmzfile(outfilekmz, 'phaena.kml', kmlDoc)
        run_earth(outfilekmz)

def main():
    parser = OptionParser()
    parser = OptionParser(usage="%prog [-f] [-q] [-o]", version="%prog 1.0")
    parser.add_option("-d", "--datafile",dest="datafile",action="store", help="example:--datafile", metavar="filename")
    parser.add_option("-p", "--polygonkml",dest="polygonkml",action="store", help="example:--datafile", metavar="filename")
    parser.add_option("-o", "--outfilekmz",dest="outfilekmz",action="store", help="example:--outfilekmz", metavar="filename")
    options, args = parser.parse_args()
    print options, args
    #print options.datafile
    if len(args) != 0:
        parser.error("incorrect number of arguments")
    if options.datafile:
        global datafile
        datafile = options.datafile
        print datafile
    if options.polygonkml:
        global polygonkml
        polygonkml = options.polygonkml
        print polygonkml
    if options.outfilekmz:
        global outfilekmz
        outfilekmz = options.outfilekmz
        print outfilekmz
    run()
    

if __name__ == '__main__':
	
    print "-" * 20, "PHAENA", "-" * 20
    print """\
     ____  _   _    __    ____  _  _    __   
    (  _ \( )_( )  /__\  ( ___)( \( )  /__\  
     )___/ ) _ (  /(__)\  )__)  )  (  /(__)\ 
    (__)  (_) (_)(__)(__)(____)(_)\_)(__)(__)
        """
    main()		

